package com.seagox.chat.chat.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seagox.chat.chat.entity.ChatContact;
import com.seagox.chat.chat.entity.ChatMessage;
import com.seagox.chat.chat.entity.ChatRoom;
import com.seagox.chat.chat.mapper.ChatContactMapper;
import com.seagox.chat.chat.mapper.ChatMessageMapper;
import com.seagox.chat.chat.mapper.ChatRoomMapper;
import com.seagox.chat.chat.service.IChatContactService;
import com.seagox.chat.common.ResultData;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 聊天联系人 服务实现类
 */
@Service
public class ChatContactService extends ServiceImpl<ChatContactMapper, ChatContact> implements IChatContactService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;
    
    @Autowired
    private ChatContactMapper chatContactMapper;
    
    @Autowired
    private ChatRoomMapper chatRoomMapper;

    @Override
    public ResultData queryListByUserId(String userId, String name) {
    	LambdaQueryWrapper<ChatContact> qw = new LambdaQueryWrapper<>();
    	qw.eq(ChatContact::getSource, userId).eq(ChatContact::getFlag, 1)
    	.like(!StringUtils.isEmpty(name), ChatContact::getName, name)
    	.orderByDesc(ChatContact::getUpdateTime);
        return ResultData.success(chatContactMapper.selectList(qw));
    }
    
    @Transactional
	@Override
	public ResultData delete(String id, String userId, String sessionId) {
		ChatContact chatContact = new ChatContact();
		chatContact.setId(id);
		chatContact.setFlag(0);
		chatContact.setType(1);
		chatContact.setUnread(0);
		chatContact.setContent("");
		chatContactMapper.updateById(chatContact);
		
		LambdaUpdateWrapper<ChatMessage> qw = new LambdaUpdateWrapper<>();
		qw.eq(ChatMessage::getSessionId, sessionId).eq(ChatMessage::getTarget, userId);
		chatMessageMapper.delete(qw);
		return ResultData.success(null);
	}

	@Override
	public ResultData cleanUnread(String id) {
		ChatContact chatContact = new ChatContact();
		chatContact.setId(id);
		chatContact.setUnread(0);
		chatContactMapper.updateById(chatContact);
		return ResultData.success(null);
	}
	
	@Transactional
	@Override
	public ResultData createChat(String userId, String name, String data) {
		String msgid = String.valueOf(System.currentTimeMillis());
		JSONArray userData = JSONArray.parseArray(data);
		if (userData.size() > 1) {
			// 群聊
			List<String> nameList = new ArrayList<>();
			List<String> memberList = new ArrayList<>();
			memberList.add(userId);
			for (int i = 0; i < userData.size(); i++) {
				JSONObject user = userData.getJSONObject(i);
				nameList.add(user.getString("name"));
				memberList.add(user.getString("id"));
			}
			ChatRoom chatRoom = new ChatRoom();
			chatRoom.setClassify(2);
			chatRoom.setMembers(String.join(",", memberList));
			if(nameList.size() > 5) {
				chatRoom.setName(String.join("、", nameList.subList(0, 5)));
			} else {
				chatRoom.setName(String.join("、", nameList));
			}
			chatRoom.setOwner(userId);
			chatRoomMapper.insert(chatRoom);

			List<ChatContact> chatContactList = new ArrayList<>();
			ChatContact selfContact = new ChatContact();
			selfContact.setClassify(2);
			selfContact.setTarget(userId);
			selfContact.setContent(String.join(",", nameList) + " 加入群聊");
			selfContact.setFlag(1);
			if(nameList.size() > 5) {
				selfContact.setName(String.join("、", nameList.subList(0, 5)));
			} else {
				selfContact.setName(String.join("、", nameList));
			}
			selfContact.setType(1);
			selfContact.setUnread(0);
			selfContact.setSource(userId);
			selfContact.setUpdateTime(new Date());
			selfContact.setSessionId(chatRoom.getId());
			selfContact.setMsgid(msgid);
			chatContactList.add(selfContact);
			for (int i = 0; i < userData.size(); i++) {
				JSONObject user = userData.getJSONObject(i);
				ChatContact chatContact = new ChatContact();
				chatContact.setClassify(2);
				chatContact.setTarget(userId);
				chatContact.setContent("");
				chatContact.setFlag(0);
				if(nameList.size() > 5) {
					chatContact.setName(String.join("、", nameList.subList(0, 5)));
				} else {
					chatContact.setName(String.join("、", nameList));
				}
				chatContact.setType(1);
				chatContact.setUnread(0);
				chatContact.setSource(user.getString("id"));
				chatContact.setSessionId(chatRoom.getId());
				chatContact.setMsgid(msgid);
				chatContactList.add(chatContact);
			}
			this.saveBatch(chatContactList);
			return ResultData.success(selfContact);
		} else {
			// 单聊
			LambdaQueryWrapper<ChatContact> qw = new LambdaQueryWrapper<>();
			qw.eq(ChatContact::getSource, userId)
					.eq(ChatContact::getTarget, userData.getJSONObject(0).getString("id"))
					.eq(ChatContact::getClassify, 1);
			ChatContact chatContact = chatContactMapper.selectOne(qw);
			if (chatContact != null) {
				chatContact.setFlag(1);
				chatContact.setUnread(0);
				chatContactMapper.updateById(chatContact);
			} else {
				List<String> nameList = new ArrayList<>();
				List<String> memberList = new ArrayList<>();
				for (int i = 0; i < userData.size(); i++) {
					JSONObject user = userData.getJSONObject(i);
					nameList.add(user.getString("name"));
					memberList.add(user.getString("id"));
				}
				nameList.add(name);
				memberList.add(userId);
				ChatRoom chatRoom = new ChatRoom();
				chatRoom.setClassify(1);
				chatRoom.setMembers(String.join(",", memberList));
				chatRoom.setName(String.join("、", nameList));
				chatRoom.setOwner(userId);
				chatRoomMapper.insert(chatRoom);
				
				
				JSONObject user = userData.getJSONObject(0);
				chatContact = new ChatContact();
				chatContact.setClassify(1);
				chatContact.setTarget(user.getString("id"));
				chatContact.setContent("");
				chatContact.setFlag(1);
				chatContact.setName(user.getString("name"));
				chatContact.setType(1);
				chatContact.setUnread(0);
				chatContact.setSource(userId);
				chatContact.setUpdateTime(new Date());
				chatContact.setAvatar(user.getString("avatar"));
				chatContact.setSessionId(chatRoom.getId());
				chatContact.setMsgid(msgid);
				chatContactMapper.insert(chatContact);
				
				ChatContact sideContact = new ChatContact();
				sideContact.setClassify(1);
				sideContact.setTarget(userId);
				sideContact.setContent("");
				sideContact.setFlag(0);
				sideContact.setName(name);
				sideContact.setType(1);
				sideContact.setUnread(0);
				sideContact.setSource(user.getString("id"));
				sideContact.setUpdateTime(new Date());
				sideContact.setAvatar(user.getString("avatar"));
				sideContact.setSessionId(chatRoom.getId());
				sideContact.setMsgid(msgid);
				chatContactMapper.insert(sideContact);
			}
			return ResultData.success(chatContact);
		}
	}
	
}
